package com.dhu.service.impl;

import com.dhu.dao.ChatMapper;
import com.dhu.dao.UserMapper;
import com.dhu.pojo.Chat;
import com.dhu.pojo.Contacts;
import com.dhu.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ChatMapper chatMapper;
    @Autowired
    private UserMapper userMapper;

    // 获取联系人
    @Override
    public List<Contacts> getContacts(int myId) {
        try {
            // 获取联系人id
            List<Chat> chatList = chatMapper.getChatByMyId(myId);
            List<Integer> ids = new ArrayList<>();
            for (Chat chat : chatList) {
                if (chat.getSender() == myId) {
                    ids.add(chat.getReceiver());
                } else if (chat.getReceiver() == myId) {
                    ids.add(chat.getSender());
                }
            }
            // 删除重复id
            LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(ids);
            ids = new ArrayList<>(hashSet);
            // 返回联系人列表
            List<Contacts> contacts = userMapper.getContactsByIds(ids);
            for (Contacts contact : contacts) {
                contact.setLastMsg(chatMapper.getLastMsg(contact.getUserId()));
                contact.setUnread(chatMapper.getUnReadNum(contact.getUserId(), myId));
            }
            return contacts;
        } catch (Exception e) {
            return null;
        }
    }

    // 获取聊天信息
    @Override
    public List<Chat> getMsg(int myId, int contactsId) {
        try {
            // 将此联系人的聊天设置为已读
            chatMapper.setMsgRead(contactsId, myId);
            return chatMapper.getMsg(myId, contactsId);
        } catch (Exception e) {
            return null;
        }
    }
}
